package com.itheima.service.front.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.util.StringUtil;
import com.itheima.dao.front.ExamPaperDao;
import com.itheima.dao.front.ExamQuestionDao;
import com.itheima.dao.store.QuestionDao;
import com.itheima.dao.store.QuestionItemDao;
import com.itheima.domain.front.ExamPaper;
import com.itheima.domain.front.ExamQuestion;
import com.itheima.domain.store.Question;
import com.itheima.domain.store.QuestionItem;
import com.itheima.factory.MapperFactory;
import com.itheima.service.front.ExamService;
import com.itheima.utils.JedisUtils;
import com.itheima.utils.TransactionUtil;
import org.apache.ibatis.session.SqlSession;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

public class ExamServiceImpl implements ExamService {
    @Override
    public List<Question> getPaper() throws IOException {
        SqlSession sqlSession = null;
        Jedis jedis = JedisUtils.getResource();
        String json1 = jedis.hget("exam", "single");
        String json2 = jedis.hget("exam","multi");
        List<Question> questions = new ArrayList<>();
        if(StringUtil.isEmpty(json1) || StringUtil.isEmpty(json2)){
            try{
                //1.获取SqlSession
                sqlSession = MapperFactory.getSqlSession();
                //2.获取Dao
                QuestionDao questionDao = MapperFactory.getMapper(sqlSession, QuestionDao.class);
                List<Question> singleAll = questionDao.findSingleAll();
                List<Question> multiAll = questionDao.findMultiAll();
                jedis.hset("exam","single",new ObjectMapper().writeValueAsString(singleAll));
                jedis.hset("exam","single",new ObjectMapper().writeValueAsString(multiAll));
                //设置jedis的存活时间
                jedis.expire("exam",60*60*24);
                Random random = new Random();
                for (int i = 0; i < 2; i++) {
                    int singnum = random.nextInt(singleAll.size());
                    questions.add(singleAll.get(singnum));
                    singleAll.remove(singnum);
                    int multinum = random.nextInt(multiAll.size());
                    questions.add(multiAll.get(multinum));
                    multiAll.remove(multinum);
                }

            }catch (Exception e){
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }else{
            List<Question> singleAll = new ObjectMapper().readValue(json1, new TypeReference<List<Question>>() {});
            List<Question> multiAll = new ObjectMapper().readValue(json2, new TypeReference<List<Question>>() {});
            Random random = new Random();
            for (int i = 0; i < 2; i++) {
                int singnum = random.nextInt(singleAll.size());
                questions.add(singleAll.get(singnum));
                singleAll.remove(singnum);
                int multinum = random.nextInt(multiAll.size());
                questions.add(multiAll.get(multinum));
                multiAll.remove(multinum);
            }
        }
        return questions;
    }

    @Override
    public boolean applyPaper(String memberId, List<ExamQuestion> examQuestionList, String createTime) {
        SqlSession sqlSession = null;
        try{
            //1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //2.获取Dao
            ExamPaperDao examPaperDao = MapperFactory.getMapper(sqlSession, ExamPaperDao.class);
            ExamQuestionDao examQuestionDao = MapperFactory.getMapper(sqlSession, ExamQuestionDao.class);

            QuestionItemDao questionItemDao = MapperFactory.getMapper(sqlSession, QuestionItemDao.class);

            //3.提交保存的试卷信息
            ExamPaper examPaper  = new ExamPaper();
            String paperId = UUID.randomUUID().toString();

            //转换日期格式字符串

            Date time = new Date(Long.parseLong(createTime));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(time);

            examPaper.setCreateTime(format);
            examPaper.setId(paperId);
            examPaper.setApplyTime(new Date());
            examPaper.setMemberId(memberId);
            examPaper.setState("1");

            int score = 0;

            //4.提交保存的试卷中的所有题目对应的答案信息
            for(ExamQuestion eq: examQuestionList) {

                //得到当前题目的正确答案
                List<QuestionItem> rightAnsByQuestionId = questionItemDao.findRightAnsByQuestionId(eq.getQuestionId());

                //如果答案数为1，则说明是单选，进行单选答案验证
                if(rightAnsByQuestionId.size()==1){
                    if(rightAnsByQuestionId.get(0).getId().equals(eq.getAnswer())){
                        score += 20;
                    };
                }else { //如果答案数不为1，则说明是多选，进行多选答案验证
                    boolean flag = true;
                    for (int i = 0; i < rightAnsByQuestionId.size(); i++) {
                        if(!eq.getAnswer().contains(rightAnsByQuestionId.get(i).getId())){
                            flag = false;
                        }
                    }
                    if(flag){
                        score+=30;
                    }
                }

                eq.setId(UUID.randomUUID().toString());
                eq.setExamPaperId(paperId);
            }

            examPaper.setScore(score);

            examPaperDao.save(examPaper);

            TransactionUtil.commit(sqlSession);
            return true;
        }catch (Exception e){
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
            //记录日志
        }finally {
            try {
                TransactionUtil.close(sqlSession);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public void deleteById(String id) {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        ExamPaperDao examPaperDao = MapperFactory.getMapper(sqlSession,ExamPaperDao.class);
        examPaperDao.deleteById(id);
        TransactionUtil.commit(sqlSession);
    }


}
